<template>
  <div class="app-container">
    <div class="search">
      <el-form
        ref="queryForm"
        class="queryForm"
        :inline="true"
        :model="formInline"
        label-width="auto"
      >
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item
              label="模型名称"
              class="formItem"
            >
              <el-input
                v-model="formInline.modelName"
                placeholder="请输入模型名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
                    <el-form-item label="所属机构" class="formItem">
                        <el-input  v-model="formInline.orgName" placeholder="请输入所属机构" clearable></el-input>
                    </el-form-item>
                </el-col> -->
          <el-col :span="4">
            <el-form-item>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-search"
                @click="handleSearch"
              >搜索</el-button>
              <el-button
                size="small"
                icon="el-icon-refresh"
                @click="handleReset"
              >重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="list">
        <el-button
          type="primary"
          class="add"
          size="small"
          icon="el-icon-plus"
          @click="handelCreate"
        >新增</el-button>
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          :header-cell-style="{background:'#eff7fd'}"
          ref="table"
          highlight-current-row
          v-loading="loading"
        >
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <span>{{(pageNum - 1) * pageSize + scope.$index + 1}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="模型名称"
            prop="modelName"
            align="center"
          ></el-table-column>
          <el-table-column
            label="模型描述"
            prop="modelDescribe"
            align="center"
          ></el-table-column>
          <el-table-column
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.status == 0 || scope.row.status == 1"
                @click.stop="handleCheck(scope.row)"
              >编辑</el-button>
              <el-button
                size="mini"
                type="text"
                :disabled="scope.row.status == 0 || scope.row.status == 1"
                @click.stop="handleDelete(scope.row)"
              >删除</el-button>
              <el-button
                size="mini"
                type="text"
                v-if="scope.row.status == 0"
                disabled
              >待执行</el-button>
              <el-button
                size="mini"
                type="text"
                v-else-if="scope.row.status == 1"
                disabled
              >执行中</el-button>
              <el-button
                size="mini"
                type="text"
                v-else
                @click.stop="handleDown(scope.row)"
              >执行</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            @size-change="sizeChange"
            @current-change="pageChange"
            :current-page="pageNum"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="showFlag"
      width="60%"
      class="dialog"
      center
    >
      <div class="message">
        <div class="module">
          <el-form
            ref="editForm"
            class="editForm"
            :rules="rule"
            :inline="true"
            :model="editForm"
            label-width="100px"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item
                  label="模型名称"
                  class="formItem"
                  prop="modelName"
                >
                  <el-input
                    v-model="editForm.modelName"
                    placeholder="请输入模型名称"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="18">
                <el-form-item
                  label="模型描述"
                  class="formItem"
                >
                  <el-input
                    v-model="editForm.modelDescribe"
                    type="textarea"
                    placeholder="请输入模型名称"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-tabs v-model="active">
            <el-tab-pane
              label="指标设置"
              name="first"
            >
              <div class="list">
                <el-button
                  type="primary"
                  class="add"
                  size="mini"
                  icon="el-icon-plus"
                  @click="addScore"
                >添加指标</el-button>
                <span>当前指标权重：{{weightTotal}}%</span>
                <el-table
                  :data="editForm.list"
                  border
                  style="width: 100%"
                  :header-cell-style="{background:'#eff7fd'}"
                  ref="table"
                  highlight-current-row
                >
                  <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="100"
                  ></el-table-column>
                  <el-table-column
                    label="指标名称"
                    prop="indicatorName"
                    align="center"
                    width="250px"
                  >
                    <template slot-scope="scope">
                      <el-select
                        style="width: 100%;"
                        v-model="scope.row.indicatorName"
                        filterable
                        @change="indicatorChange(scope)"
                      >
                        <el-option
                          v-for="(dict, index) in scoreOptions"
                          placeholder="请选择指标"
                          :label="dict.label"
                          :value="dict.value"
                          :key="index"
                        ></el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="权重"
                    prop="weight"
                    align="center"
                    width="200px"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-if="scope.row.positiveOrNegative == 0"
                        @change="computedWeight"
                        v-model="scope.row.weight"
                        placeholder="请输入权重"
                        clearable
                      />
                      <span v-else>——</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="正/负向指标"
                    prop="positiveOrNegative"
                    align="center"
                    width="120px"
                    :formatter="typeFormatterSign"
                  ></el-table-column>
                  <el-table-column
                    label="指标性质"
                    prop="characteristic"
                    align="center"
                    :formatter="typeFormatter"
                  ></el-table-column>
                  <el-table-column
                    label="设置指标"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        @click.stop="handleEditSet(scope.row)"
                      >设置</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    align="center"
                  >
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        @click.stop="handleEditDelete(scope)"
                      >删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
          <div
            slot="footer"
            class="dialog-footer"
          >
            <el-button
              type="primary"
              @click="handleSubmit"
            >保存</el-button>
            <!-- <el-button type="primary" @click="handleEditReset">重置</el-button> -->
            <el-button
              type="primary"
              @click="showFlag = false"
            >取消</el-button>
          </div>
        </div>
        <el-dialog
          width="50%"
          title="指标设置"
          :visible.sync="innerVisible"
          append-to-body
        >
          <div class="list">
            <el-button
              type="primary"
              class="add"
              size="mini"
              icon="el-icon-plus"
              @click="addSetScore"
            >添加</el-button>
            <el-table
              :data="scoreList"
              border
              style="width: 100%"
              :header-cell-style="{background:'#eff7fd'}"
              ref="table1"
              highlight-current-row
            >
              <el-table-column
                label="序号"
                type="index"
                align="center"
                width="100"
              ></el-table-column>
              <el-table-column
                label="区间最小值（不含等于）"
                prop="min"
                width="200px"
                align="center"
                v-if="character == '0'"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.min"
                    placeholder="请输入最小值"
                    clearable
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="区间最大值（含等于）"
                prop="max"
                align="center"
                width="200px"
                v-if="character == '0'"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.max"
                    placeholder="请输入最大值"
                    clearable
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="判断条件"
                prop="conditions"
                align="center"
                v-if="character == '1'"
              >
                <template slot-scope="scope">
                  <el-select
                    style="width: 100%;"
                    v-model="scope.row.conditions"
                  >
                    <el-option
                      v-for="(dict, index) in pdOptions"
                      placeholder="请选择判断条件"
                      :label="dict.label"
                      :value="dict.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="指标等级"
                prop="conditions"
                align="center"
                v-if="character == '2'"
              >
                <template slot-scope="scope">
                  <el-select
                    style="width: 100%;"
                    v-model="scope.row.conditions"
                  >
                    <el-option
                      v-for="(dict, index) in levelOptions"
                      placeholder="请选择指标等级"
                      :label="dict.label"
                      :value="dict.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                label="得分"
                prop="score"
                align="center"
              >
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.score"
                    placeholder="请输入得分"
                    clearable
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    @click.stop="handleSetDelete(scope)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div
              slot="footer"
              class="dialog-footer"
            >
              <el-button
                type="primary"
                @click="handelSetSubmit"
              >保存</el-button>
              <el-button
                type="primary"
                @click="innerVisible = false"
              >取消</el-button>
            </div>
          </div>
        </el-dialog>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getManageList,
  getRuleList,
  getScoringManages,
  getScoringInstallList,
  scoringInstall,
  createRule,
  updateRule,
  deleteModel,
  computeModel,
} from '@/api/gradManage.js'
import { getField } from '@/api/user.js'
export default {
  data() {
    return {
      // 搜索表单
      formInline: {},
      //列表信息
      tableData: [],
      loading: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
      title: '',
      editForm: {
        list: [],
      },
      orgId: undefined,
      managementId: undefined,
      weightTotal: 0,
      //指标类型
      scoreData: [],
      scoreOptions: [],
      positiveOrNegative_types: [
        { label: '正向指标', value: 0 },
        { label: '负向指标', value: 1 },
      ],
      // 指标性质
      characteristic_types: [
        { label: '区间', value: '0' },
        { label: '判断', value: '1' },
        { label: '等级', value: '2' },
      ],
      showFlag: false,
      active: 'first',
      rule: {
        modelName: [
          { required: true, message: '请输入模型名称', trigger: 'blur' },
        ],
      },
      //指标设置
      innerVisible: false,
      scoreList: [],
      character: undefined,
      //判断条件
      pdOptions: [
        { label: '是', value: '0' },
        { label: '否', value: '1' },
      ],
      levelOptions: [],
    }
  },
  created() {
    let params = {
      page: 1,
      size: 100,
      code: 'LEVEL',
    }
    getField(params).then((res) => {
      if (res.status) {
        this.levelOptions = res.data.records.map((item) => {
          return { label: item.fieldName, value: item.fieldCode }
        })
      }
    })
    getScoringManages().then((res) => {
      if (res.status) {
        this.scoreData = res.data
        this.scoreOptions = res.data.map((item) => {
          return { label: item.indicatorName, value: item.indicatorName }
        })
      }
    })
    this.handleSearch()
  },
  methods: {
    //搜索
    handleSearch() {
      let formLine = this.formInline
      let params = {
        ...formLine,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        type: '1',
      }
      this.loading = true
      getManageList(params).then((res) => {
        if (res.status) {
          this.loading = false
          this.tableData = res.data.records
          this.total = Number(res.data.total)
        }
      })
    },
    sizeChange(val) {
      this.pageSize = val
      this.handleSearch()
    },
    pageChange(val) {
      this.pageNum = val
      this.handleSearch()
    },
    //重置
    handleReset() {
      this.formInline = {}
      this.handleSearch()
    },
    //新增
    handelCreate() {
      this.title = '新增'
      this.showFlag = true
      this.editForm = {
        list: [],
      }
      this.computedWeight()
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
    },
    //编辑
    handleCheck(row) {
      this.title = '编辑'
      this.showFlag = true
      this.$nextTick(() => {
        this.$refs['editForm'].clearValidate()
      })
      getRuleList({ orgId: row.orgId, modelName: row.modelName }).then(
        (res) => {
          if (res.status) {
            this.editForm = res.data
            this.computedWeight()
            this.orgId = row.orgId
          }
        }
      )
    },
    //列表删除
    handleDelete(row) {
      this.$confirm('确定删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        deleteModel({ orgId: row.orgId, modelName: row.modelName }).then(
          (res) => {
            if (res.status) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.handleSearch()
            }
          }
        )
      })
    },
    //执行
    handleDown(row) {
      computeModel({ modelName: row.modelName }).then((res) => {
        if (res.status) {
          this.$message({
            type: 'success',
            message: res.msg,
          })
        }
      })
    },
    //新增或编辑保存
    handleSubmit() {
      let list = this.editForm.list
      let s = new Set()
      list.forEach((i) => s.add(i.indicatorName))
      if (list.length != s.size) {
        this.$message({
          type: 'error',
          message: '指标有重复,请更改!',
        })
        return
      }
      if (this.weightTotal > 100) {
        this.$message({
          type: 'error',
          message: '当前指标权重总和不能大于100!',
        })
        return
      }
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          let params
          if (this.title == '新增') {
            params = this.editForm.list.map((item) => {
              return {
                managementId: item.id,
                weight: item.weight,
                orgId: null,
                modelName: this.editForm.modelName,
                modelDescribe: this.editForm.modelDescribe,
              }
            })
            createRule(params).then((res) => {
              if (res.status) {
                this.showFlag = false
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                })
                this.handleSearch()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
          } else if (this.title == '编辑') {
            params = this.editForm.list.map((item) => {
              return {
                managementId: item.id,
                weight: item.weight,
                orgId: this.orgId,
                modelName: this.editForm.modelName,
                modelDescribe: this.editForm.modelDescribe,
              }
            })
            updateRule(params).then((res) => {
              if (res.status) {
                this.showFlag = false
                this.$message({
                  type: 'success',
                  message: '操作成功!',
                })
                this.handleSearch()
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg,
                })
              }
            })
          }
        }
      })
    },
    //编辑重置
    handleEditReset() {
      this.editForm = {
        list: [],
      }
    },
    //选择指标
    indicatorChange(scope) {
      let arr = this.editForm.list.filter((ite) => {
        return ite.indicatorName == scope.row.indicatorName
      })
      if (arr.length > 1) {
        this.$message({
          type: 'warning',
          message: '该指标已设置,请重新选择!',
        })
        return
      }
      let indicatorname = scope.row.indicatorName
      let indicatorData = this.scoreData.filter((item) => {
        return item.indicatorName == indicatorname
      })[0]
      console.log(indicatorData)
      let { characteristic, id, indicatorName, positiveOrNegative } =
        indicatorData
      this.$set(this.editForm.list, scope['$index'], {
        characteristic,
        id,
        indicatorName,
        positiveOrNegative,
        weight: 0,
      })
    },
    //计算权重
    computedWeight() {
      this.weightTotal = this.editForm.list
        .map((item) => Number(item.weight))
        .reduce((cur, prev) => cur + prev, 0)
    },
    //添加指标
    addScore() {
      this.editForm.list.push({ positiveOrNegative: 0, weight: 0 })
    },
    //删除指标
    handleEditDelete(scope) {
      this.editForm.list.splice(scope['$index'], 1)
    },
    //设置指标
    handleEditSet(row) {
      if (!row.indicatorName) {
        this.$message({
          type: 'warning',
          message: '请先选择指标!',
        })
        return
      }
      if (row.characteristic == '0') {
        this.character = '0'
      } else if (row.characteristic == '1') {
        this.character = '1'
      } else if (row.characteristic == '2') {
        this.character = '2'
      }
      this.innerVisible = false
      getScoringInstallList({ managementId: row.id }).then((res) => {
        if (res.status) {
          this.managementId = row.id
          this.innerVisible = true
          if (row.characteristic == '0') {
            this.scoreList = res.data.map((item) => {
              let conditions = item.conditions.split('-')
              return { ...item, min: conditions[0], max: conditions[1] }
            })
          } else {
            this.scoreList = res.data
          }
        }
      })
    },
    //设置添加
    addSetScore() {
      this.scoreList.push({})
    },
    handleSetDelete(scope) {
      this.scoreList.splice(scope['$index'], 1)
    },
    handelSetSubmit() {
      let list
      if (this.character == '0') {
        list = this.scoreList.map((item) => {
          return {
            managementId: this.managementId,
            condition: item.min + '-' + item.max,
            score: item.score,
            type: 0,
          }
        })
      } else if (this.character == '1') {
        list = this.scoreList.map((item) => {
          return {
            managementId: this.managementId,
            condition: item.conditions,
            score: item.score,
            type: 1,
          }
        })
      } else if (this.character == '2') {
        list = this.scoreList.map((item) => {
          return {
            managementId: this.managementId,
            condition: item.conditions,
            score: item.score,
            type: 2,
          }
        })
      }
      let orgId = this.title == '新增' ? null : this.orgId
      let params = {
        managementId: this.managementId,
        orgId: orgId,
        jrfkScoringManagementInstallEntityList: list,
      }
      scoringInstall(params).then((res) => {
        if (res.status) {
          this.innerVisible = false
          this.$message({
            type: 'success',
            message: '操作成功!',
          })
        }
      })
    },
    typeFormatterSign(r, c, v, i) {
      let list = this.positiveOrNegative_types.filter((item) => item.value == v)
      return list.length > 0 ? list[0].label : v
    },
    typeFormatter(r, c, v, i) {
      let list = this.characteristic_types.filter((item) => item.value == v)
      return list.length > 0 ? list[0].label : v
    },
  },
}
</script>

<style scoped lang="scss">
.search {
  padding: 20px 0 20px 20px;
  background:#fff;
}
.list {
  .add {
    margin-bottom: 10px;
    margin-right: 10px;
  }
  .pagination {
    width: 100%;
    margin-top: 10px;
    display: flex;
    justify-content: center;
  }
}
.formItem {
  width: 100%;
  /deep/.el-form-item__content {
    width: calc(100% - 125px);
    /deep/.el-select,
    /deep/.el-cascader {
      width: 100%;
    }
    .w100 {
      width: 100% !important;
    }
  }
}

.dialog-footer {
  margin-top: 20px;
  text-align: center;
}

/deep/.el-dialog__body {
  padding-bottom: 20px;
}
</style>